# -*- coding: utf-8 -*-

r"""
fuwa 
fuwa list
of controller
"""
from framework.admincontroller import AdminController
from models.fuwalist import FuwaListModel
from framework.mongo import MongoModel
from models.index import IndexModel
import tornado.web
import json
import re
import time
import tornado.httpclient

class FuwaCtrl(AdminController):
    """action index method"""
    err = dict(err=1, msg='')

    @tornado.web.authenticated
    def get(self, *args):
        """fuwa handler"""
        if not args or args[0] == '/' or (not args[0]):
            self.render("fuwa/index.html", listurl='/fuwa/list')
            return
        # fuwa list
        if args[0] == '/list' or args[0] == '/list/':
            self.write(json.dumps(self.fuwa_list()))
        # fuwa info
        elif args[0].find('/info/') == 0:
            p = re.match(r'^/info/([0-9]+)$', args[0])
            if not p:
                self.write_error(404)
                return
            i = self.fuwa_info(fuwa_key=p.group(1))
            if not i:
                self.write_error(404)
                return
            if i.get('htime'):
                i['htime'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(i.get('htime'))))
            else:
                i['htime'] = 0
            self.render('fuwa/info.html', fuwa=i)
            return
        # fuwa number total
        elif args[0] == '/number' or args[0] == '/number/':
            i = self.fuwaid_num_handler()
            if not i:
                self.write_error(404)
                return
            # self.write(json.dumps(i))
            self.render('fuwa/number.html', numbers=i)
            return
        # fuwa i list index
        elif args[0] == '/i' or args[0] == '/i/':
            self.render("fuwa/index.html", listurl='/fuwa/i/list')
            return
        # fuwa i list
        elif args[0] == '/i/list' or args[0] == '/i/list/':
            self.write(json.dumps(self.fuwa_kind_list('i')))
            return
        # fuwa c list
        elif args[0] == '/c' or args[0] == '/c/':
            self.render("fuwa/index.html", listurl='/fuwa/c/list')
            return
        # fuwa i list
        elif args[0] == '/c/list' or args[0] == '/c/list/':
            self.write(json.dumps(self.fuwa_kind_list('c')))
            return
        # fuwa hide ui
        elif args[0] == '/hide' or args[0] == '/hide/':
            m = FuwaListModel()
            loc = m.get_hide_loca()
            self.render('fuwa/hide.html', locs=loc)
            return
        # fuwa hide list data
        elif args[0] == '/hide/info' or args[0] == '/hide/info/':
            m = FuwaListModel()
            i, c = m.get_hide_count()
            data = list()
            data.append({'label': u'缘份福娃', 'value': i})
            data.append({'label': u'寻宝福娃', 'value': c})
            e = dict(err=0, msg=data)
            self.ajax_out(**e)
            return
        # fuwa hide list for i
        elif args[0] == '/hide/i/list' or args[0] == '/hide/i/list/':
            self.write(json.dumps(self.get_hide_list('i')))
            return
        # fuwa hide list for c
        elif args[0] == '/hide/c/list' or args[0] == '/hide/c/list/':
            self.write(json.dumps(self.get_hide_list('c')))
            return
        # fuwa cauth ui
        elif args[0] == '/cau' or args[0] == '/cau/':
            self.render('fuwa/cau.html')
            return
        # fuwa cauth count
        elif args[0] == '/cau/info' or args[0] == '/cau/info/':
            m = FuwaListModel()
            i, c = m.get_cau_count()
            data = list()
            data.append({'label': u'缘份福娃', 'value': i})
            data.append({'label': u'寻宝福娃', 'value': c})
            e = dict(err=0, msg=data)
            self.ajax_out(**e)
            return
        # fuwa cauth list
        elif args[0] == '/cau/c/list' or args[0] == '/cau/c/list/':
            self.write(json.dumps(self.get_cau_list('c')))
            return
        # fuwa cauth list i
        elif args[0] == '/cau/i/list' or args[0] == '/cau/i/list/':
            self.write(json.dumps(self.get_cau_list('i')))
            return
        # fuwa awarded ui
        elif args[0] == '/awarded' or args[0] == '/awarded/':
            self.render('fuwa/awarded.html')
            return
        # fuwa awarded list
        elif args[0] == '/awarded/list' or args[0] == '/awarded/list/':
            self.write(json.dumps(self.get_awarded_list()))
            return
        else:
            self.write_error(404)
            return

    def fuwa_info(self, fuwa_key=None):
        """
        get the fuwa info
        :param fuwa_key: number id
        :return: redis hash fuwa_i_id or fuwa_c_id key all value
        """
        fuwa_m = FuwaListModel()
        return fuwa_m.get_fuwa_info(fuwa_key)

    def fuwa_list(self):
        """handler fuwa list request"""
        # start = int(self.get_argument("start", 0))
        # size = int(self.get_argument("length", 0))
        # draw = int(self.get_argument("draw", 1))
        # if not size:
        #    size = 50
        # if start:
        #    start = (start / size) + 1
        # else:
        #    start = 1
        start, size, draw = self.datatablepage()
        if start:
            start = (start / size) + 1
        else:
            start = 1
        fuwa_m = FuwaListModel()
        l = fuwa_m.get_fuwa_list(start, size)
        # bootstrap datatable
        l["draw"] = draw
        # self.write(json.dumps(l))
        return l

    def fuwa_kind_list(self, k):
        """fuwa c and i list"""
        start, size, draw = self.datatablepage()
        fuwa_m = FuwaListModel()
        l = fuwa_m.get_fuwa_kind_list(k, start, size)
        # bootstrap datatable
        l["draw"] = draw
        return l

    def fuwaid_num_handler(self):
        """handle fuwa id number"""
        # start, size, draw = self.datatablepage()
        start = 0
        size = 1
        m = IndexModel()
        i = m.get_fuwa(start, size)
        if not i:
            return
        # f = None
        data = list()
        l = i[0].get('fuwa_id_num')
        # for f in i:
        #    break
        # l = f.get("fuwa_id_num")
        if not l:
            return
        keys = l.keys()
        t_l = list()
        try:
            keys = map(int, keys)
        except ValueError:
            for key in keys:
                try:
                    t = int(key)
                    t_l.append(t)
                except ValueError:
                    pass
            keys = t_l
        keys.sort()
        keys = map(str, keys)
        for k in keys:
            data.append({
                'day': time.strftime('%Y-%m-%d', time.localtime(i[0].get('sync_time'))),
                'number': k,
                'value': l.get(k)
             })
        return data

    def get_hide_list(self, kind):
        """get fuwa hide"""
        start, size, draw = self.datatablepage()
        m = FuwaListModel()
        l = m.get_hide_list(kind, start, size)
        l['draw'] = draw
        return l

    def get_cau_list(self, kind):
        """get fuwa cauth"""
        start, size, draw = self.datatablepage()
        m = FuwaListModel()
        l = m.get_cau_list(kind, start, size)
        l['draw'] = draw
        return l

    def get_awarded_list(self):
        """get fuwa awarded"""
        start, size, draw = self.datatablepage()
        m = FuwaListModel()
        l = m.get_awarded_list(start, size)
        l['draw'] = draw
        return l

    def datatablepage(self):
        """bootstrap data table page"""
        start = int(self.get_argument("start", 0))
        size = int(self.get_argument("length", 0))
        draw = int(self.get_argument("draw", 1))
        if not size:
            size = 50
        return start, size, draw
